import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:myapp/http/dio_instance.dart';

import '../../repository/api.dart';
import '../../repository/datas/home_baner_data.dart';
import '../../repository/datas/home_list_data.dart';

///https://wanandroid.com/blog/show/2 wanandroid 开放api地址
class HomeViewModel with ChangeNotifier {
  int pageCount = 0;
  List<HomeBannerData>? bannerList;
  List<HomeListItemData>? listItemData = [];

  //获取Banner
  Future getBanner() async {
    List<HomeBannerData>? list = await Api.instance.getBanner();
    bannerList = list ?? [];
    //通知 provider 值有变化了
    notifyListeners();
  }

  Future initListData(bool loadMore,{ValueChanged<bool>? callback}) async {
    if (loadMore) {
      pageCount++;
    } else {
      pageCount = 0;
      listItemData?.clear();
    }

    ///先获取置顶数据
    getTopList(loadMore).then((topList) {
      if (!loadMore) {
        listItemData?.addAll(topList ?? []);
      }
      ///获取首页列表
      getHomeList(loadMore).then((allList) {
        listItemData?.addAll(allList ?? []);
        ///刷新数据
        notifyListeners();
        //回调出去
        callback?.call(loadMore);
      });
    });
  }

  //获取首页文章列表
  //bool loadMore 是否为加载更多数据
  Future<List<HomeListItemData>?> getHomeList(bool loadMore) async {
    List<HomeListItemData>? list = await Api.instance.getHomeList("$pageCount");
    if (list != null && list.isNotEmpty) {
      return list;
    } else {
      //已经没新的数据
      if (loadMore && pageCount > 0) {
        pageCount--;
      }
      return [];
    }
  }

  //获取首页文章列表
  Future<List<HomeListItemData>?> getTopList(bool loadMore) async {
    //todo 如果有更多的置顶数据，会有问题，因为置顶数据没有变化
    if (loadMore) {
      return [];
    }
    List<HomeListItemData>? list = await Api.instance.getHomeTopList();
    return list;
  }

  Future collectOrNO(bool isCollect, String? id,int index) async{
   bool? success ;
   if(isCollect){
    success = await Api.instance.collect(id);
   }else{
     success = await Api.instance.unCollect(id);
   }
   if( success == true){
     listItemData?[index].collect = isCollect;
     notifyListeners();
   }
  }
}
